package com.gitee.sparta.core.cluster.strategy;

import com.gitee.sparta.core.bean.cluster.ClusterProtocol;
import com.gitee.sparta.core.bean.cluster.ServerBean;
import com.gitee.sparta.core.cluster.balance.LoadBalance;
import com.gitee.sparta.core.property.SpartaCoreProperties;
import io.netty.channel.ChannelHandlerContext;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.nio.channels.SocketChannel;

/**
 * <p>
 *      读取数据的策略
 * </p>
 *
 * @author zyred
 * @since v 0.0.2
 */
public abstract class Strategy {

    protected final RedissonClient client;
    protected final LoadBalance loadBalance;
    protected final SpartaCoreProperties properties;

    public Strategy(RedissonClient client,
                    LoadBalance loadBalance,
                    SpartaCoreProperties properties) {
        this.client = client;
        this.loadBalance = loadBalance;
        this.properties = properties;
    }

    /**
     * 执行处理
     * @param ctx           netty 上下文
     * @param sc            nio socket channel
     * @param cp            参数
     */
    abstract public void handle(ChannelHandlerContext ctx, SocketChannel sc, ClusterProtocol cp);


    /**
     * 从服务注册表中移除 client
     *
     * @param sid       server id
     */
    protected void removeToServerTable(Integer sid) {
        RMap<Integer, ServerBean> map = this.client.getMap(this.properties.getServerTable());
        map.remove(sid);
    }
}
